/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-11-10 16:49:18
 * @LastEditTime: 2023-01-09 11:18:12
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import { Modal } from 'antd';
import {
  SET_SELECT_FOND,
  SET_SELECT_AT,
  SET_TPL_TYPE,
  SET_METHOD_TYPE,
  SET_SELECTED_ITEM,
  SET_TEMPLATE_LIST,
  ADD_TEMPLATE,
  EDIT_TEMPLATE,
  DELETE_TEMPLATE,
  TEMP_TYPE_CLASSIFY_EXPORT,
  TEMP_TYPE_CLASSIFY_IMPORT
} from '../constants';
import { TemplateManageReducer } from '../reducers/TemplateManageReducer';
import {
  fetchTemplateListByPage,
  addExcelTemplate,
  editExcelTemplate,
  delectExcelTemplate
} from '@/api/accession';
import { EnumTemplateTypes } from '@/view/system/TemplateManage/dictionaries';
const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  // 模板类型：0-excel导入；1-excel导出；2-CD导入；3-CD导出；4-SIP导入；5-SIP导出；
  tplType: 0,
  // 导入（出）类型：1-excel；2-光盘；3-SIP
  methodType: 0,
  tplTypeList: [],
  selectItems: [],
  templateList: [],
  typeStatusList: [
    { code: EnumTemplateTypes.ExcelImport, name: 'Excel导入模板', type: TEMP_TYPE_CLASSIFY_IMPORT },
    { code: EnumTemplateTypes.ExcelExport, name: 'Excel导出模板', type: TEMP_TYPE_CLASSIFY_EXPORT },
    { code: EnumTemplateTypes.CDImport, name: '光盘导入模板', type: TEMP_TYPE_CLASSIFY_IMPORT },
    { code: EnumTemplateTypes.CDExport, name: '光盘导出模板', type: TEMP_TYPE_CLASSIFY_EXPORT },
    { code: EnumTemplateTypes.SipImport, name: 'sip导入模板', type: TEMP_TYPE_CLASSIFY_IMPORT },
    { code: EnumTemplateTypes.SipExport, name: 'sip导出模板', type: TEMP_TYPE_CLASSIFY_EXPORT },
    {
      code: EnumTemplateTypes.DBFImport,
      name: 'DBF数据库导入模板',
      type: TEMP_TYPE_CLASSIFY_IMPORT
    },
    {
      code: EnumTemplateTypes.DBFExport,
      name: 'DBF数据库导出模板',
      type: TEMP_TYPE_CLASSIFY_EXPORT
    }
  ]
};
const TemplateManageContext = createContext();
const TemplateManageContextProvider = (props) => {
  const [state, dispatch] = useReducer(TemplateManageReducer, initialState);
  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    setTplType(data) {
      dispatch({ type: SET_TPL_TYPE, data });
    },
    setMethodType(data) {
      dispatch({ type: SET_METHOD_TYPE, data });
    },
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },
    /**
     * @description: 请求档案分类列表
     * @param {object} params 请求参数
     * @return {*}
     */
    getTemplateList(params) {
      return new Promise((resolve, reject) => {
        fetchTemplateListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_TEMPLATE_LIST, data: data.results });
            resolve(res);
          })
          .catch((err) => {
            dispatch({ type: SET_TEMPLATE_LIST, data: [] });
            reject(err);
          });
      });
    },
    /* 增加报表 */
    addTemplateTypeList(params) {
      return new Promise((resolve, reject) => {
        addExcelTemplate(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_TEMPLATE, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    /* 修改报表 */
    editTemplateList(params) {
      return new Promise((resolve, reject) => {
        editExcelTemplate(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_TEMPLATE, data });
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },
    /**
     * @description: 删除
     * @param {*} id 删除的id
     * @param {*} content 弹窗展示内容
     * @return {*}
     */
    deleteTemplateFunc(id, content = '确认删除该光盘容量？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          delectExcelTemplate(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_TEMPLATE, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };
  const filters = {
    typeFilter(id) {
      return state.typeStatusList.find((item) => item.code === id)?.name || '-';
    }
  };
  useEffect(() => {}, []);
  return (
    <TemplateManageContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </TemplateManageContext.Provider>
  );
};
export const useTemplateManageContext = () => {
  return useContext(TemplateManageContext);
};
export { TemplateManageContext, TemplateManageContextProvider };
